<!-- 编辑弹窗 -->
<template>
    <ele-modal
      width="40%"
      :movable="false"
      :visible="visible"
      :close-on-click-modal="true"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改产品信息' : '添加产品信息'"
      @update:visible="updateVisible"
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  style="margin-top: -10px">        
        <el-row :gutter="24">
          <el-col :md="12" :sm="24">
              <el-form-item label="产品编号:" prop="code">
                <el-input v-model="form.code"  placeholder="不填系统自动生成"   >
                </el-input>
              </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24">
            <el-form-item label="产品名称:" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称"   >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24" >
            <el-form-item label="类型:" prop="typeId">
              <el-select  v-model="form.typeId" filterable clearable placeholder="请选择类型" style="width:100%" @change="unitchange">
                <el-option v-for="item in CPLXDatas" :key="item.id" :label="item.name" :value="item.id"  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24" >
            <el-form-item label="单位:" >
              <el-select  v-model="form.unitId" filterable allow-create clearable placeholder="请选择单位" style="width:100%" @change="unitchange">
                <el-option v-for="item in dicts" :key="item.id" :label="item.name" :value="item.id"  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24" >
            <el-form-item label="规格:" >
              <el-input v-model="form.spc" placeholder="请输入规格"   />
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24" >
            <el-form-item label="颜色:" >
              <el-select  v-model="form.colorId" filterable allow-create clearable placeholder="请选择颜色" style="width:100%" @change="unitchange">
                <el-option v-for="item in YSDatas" :key="item.id" :label="item.name" :value="item.id"  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24" >
            <el-form-item label="提成类型:" prop="commissionType">
              <el-select  v-model="form.commissionType" filterable  clearable placeholder="请选择提成类型" style="width:100%" @change="changecommissionType" >
                <el-option v-for="item in codeTypes" :key="item.Key" :label="item.Value" :value="item.Key"  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24">
            <el-form-item label="提成方式:"  prop="commissionMethod">
              <el-select v-model="form.commissionMethod" filterable  clearable @change="changecommissionMethod" >                       
                <el-option v-for="(item) in commissionMethodDatas" :key="item.Key" :label="item.Value" :value="item.Key"  />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :md="12" :sm="24" >
            <el-form-item label="销售价:"  prop="salePrice">
              <el-input v-model="form.salePrice" placeholder="请输入销售价"   />
            </el-form-item>
          </el-col>
          <el-col :md="12" :sm="24" >
            <el-form-item label="采购价:" prop="purPrice">
              <el-input v-model="form.purPrice" placeholder="请输入采购价"   />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >安全库存列表</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div style="width: 30%;color:var(--color-primary)" > 
                <el-button icon="el-icon-plus" style="width: 100%;" @click="AddScaleWarehouse" v-permission="'Basic_Product_AddList'" >新增 </el-button>
              </div>
          </div>
        </div> 
        <el-table :data="form.safetystockItems" ref="safetystockItems"  :border="true" style="width: 100%"  >
          <el-table-column type="index" width="50" align="center" label="序号" fixed='left' />
          <el-table-column label="仓库" align="center"  >
            <template slot-scope="{ row ,$index }">
              <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'safetystockItems.'+ $index+'.warehouseId'" :rules="itemRules.warehouseId">
                <el-select  filterable v-model="row.warehouseId" placeholder="请选择仓库" class="ele-fluid" @change="(v)=>changewarehouse(v,$index)" >
                  <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="最小数量" align="center" >
            <template slot-scope="{row,$index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'safetystockItems.'+ $index+'.minQty'" :rules="itemRules.minQty" >
                <el-input  v-model="row.minQty"  placeholder="请输入最小数量"  @keyup.native="row.minQty = row.minQty.replace(/[^\d.]/g,'');
                  row.minQty = row.minQty.replace(/\.{2,}/g,'.');
                  row.minQty = row.minQty.replace(/^\./g,'');
                  row.minQty = row.minQty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.minQty = row.minQty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center"  width="80" :resizable="false" v-if="this.btnIndex!=3">
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link v-permission="'Basic_Product_DelList'" icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" v-show="this.btnIndex!=3" :loading="loading" @click="save" v-permission="'Basic_Product_Save'">
        保存
      </el-button>
    </div>
    </ele-modal>
  </template>
  <script>

   import { QueryCommissionTypeEnum,QueryCommissionMethodEnum } from '@/api/enummanger';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { AddProduct, UpdateProduct,GetModelById } from '@/api/basicdatamanager/productmanager';
   import { isIntegerOrDecimal2 } from '@/utils/validate';

    export default {
      name: 'ProductEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      data() {
        return {
          // 表单数据
          form: {safetystockItems:[]},
          // 表单验证规则
          rules: {
            name: [{required: true,message: '请输入产品名称',trigger: 'blur'}],
            commissionType: [{required: true,message: '请选择提成类型',trigger: 'blur'}],
            commissionMethod: [{required: true,message: '请选择提成方式',trigger: 'blur'}],
            salePrice: [{validator:isIntegerOrDecimal2,trigger:'blur'}],
            purPrice: [{validator:isIntegerOrDecimal2,trigger:'blur'}],
          },
          itemRules: {
            warehouseId: [{required: true,message: '请输入仓库',trigger: 'blur'}],
            minQty: [{required: true,message: '请输入最小数量',trigger: 'blur'},{validator:isIntegerOrDecimal2,trigger:'blur'}],
          },
          //单位
          dicts:[],
          codeTypes:[],
          //单位
          CPLXDatas:[],
          //单位
          YSDatas:[],
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
          treeData:[],
          wareHouseDatas:[],
          commissionMethodDatas:[],
        };
      },

      //初始化数据
      mounted(){
        this.initDW();
      },
      methods: {
  
        /* 保存编辑 */
        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            //品牌Id 单位Id
            if(this.form.unitId && this.form.unitId==this.form.unitDesc) this.form.unitId = '';

            this.loading = true;
            const saveOrUpdate = this.isUpdate ? UpdateProduct : AddProduct;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        setData(id){
          GetModelById(id)
            .then((res) => {
              this.form = res; 
        });
      },

      //单位
      initDW(){
        QueryAllChildDictViewByCode(this.Constant.C_DW).then((data)=>{
            this.dicts = [];
            this.dicts = data;
        });

        QueryAllChildDictViewByCode(this.Constant.C_CPLX).then((data)=>{
            this.CPLXDatas = [];
            this.CPLXDatas = data;
        });

        QueryAllChildDictViewByCode(this.Constant.C_YS).then((data)=>{
            this.YSDatas = [];
            this.YSDatas = data;
        });

        QueryCommissionMethodEnum().then((data)=>{
            this.commissionMethodDatas = [];
            this.commissionMethodDatas = data;
        });

        GetAllWarehouse().then((d)=>{
          this.wareHouseDatas = [];
          this.wareHouseDatas = d;
        });

        QueryCommissionTypeEnum().then((data)=>{
            this.codeTypes = [];
            this.codeTypes = data;
        });
        
      },

      //单位选择
      unitchange(val){
        let currUnit = this.dicts.find((m)=>{
          return m.id == val;
        });

        if(!currUnit){
          this.form.unitDesc =val;
        }else{
          this.form.unitId = val;
          this.form.unitDesc =currUnit.name;
        }
      },


      /* 更新visible */
      updateVisible(value) {
        //更新父组件中的visible的值
        this.$emit('update:visible', value);
        //更新文件列表对像
      },

      /* 删除 */
      remove(_row, index) {
        this.form.safetystockItems.splice(index, 1);
      },

      AddScaleWarehouse(){
        if(!this.form.safetystockItems)this.form.safetystockItems=[];
        this.form.safetystockItems.push({
          productId:this.form.productId,
          warehouseId: '',
          minQty: '',
        });
      },

      changewarehouse(val,index){


        let warehouse = this.form.safetystockItems.find((d,i)=>{return (d.warehouseId === val && i!=index)});

        if(warehouse)
        {
          this.$message.info("当前仓库的安全库存已设置");
          this.form.safetystockItems[index].warehouseId = '';
          return 
        }
      },

      changecommissionType(val){
        this.rules.commissionType= null;
        this.rules.commissionMethod=null;
        if(val===0 || val===1){
          this.rules.commissionType= [{required: true,message: '请选择提成类型',trigger: 'blur'}];
          this.rules.commissionMethod= [{required: true,message: '请选择提成方式',trigger: 'blur'}];
        }

        if(this.form.commissionMethod){
          this.rules.commissionType= [{required: true,message: '请选择提成类型',trigger: 'blur'}];
          this.rules.commissionMethod= [{required: true,message: '请选择提成方式',trigger: 'blur'}];
        }

      },

      changecommissionMethod(val){
        this.rules.commissionType= null;
        this.rules.commissionMethod=null;
        if(val){
          this.rules.commissionType= [{required: true,message: '请选择提成类型',trigger: 'blur'}];
          this.rules.commissionMethod= [{required: true,message: '请选择提成方式',trigger: 'blur'}];
        }

        if(this.form.commissionType ===0 || this.form.commissionType ===1){
          this.rules.commissionType= [{required: true,message: '请选择提成类型',trigger: 'blur'}];
          this.rules.commissionMethod= [{required: true,message: '请选择提成方式',trigger: 'blur'}];
        }
      },
     
    },
     
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.initDW();//单位
              this.form = {};
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={safetystockItems:[]};
              this.isUpdate = false;
              this.rules.commissionType = null;
              this.rules.commissionMethod = null;
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {};
          }
        }
      }
    };
  </script>